package top.ooyyh.bytheway;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class JsonParentChild {
    public static void main(String[] args) {
        JSONObject test = JSONUtil.parseObj("{\n" +
                "  \"C1\":{\n" +
                "    \"M1\":\"yeah\",\n" +
                "    \"M2\":\"yeah\",\n" +
                "    \"C2\":{\n" +
                "      \"M3\":\"yeah\",\n" +
                "      \"M4\":\"yeah\",\n" +
                "      \"C3\":{\n" +
                "        \"M5\":\"yeah\",\n" +
                "        \"M6\":\"yeah\",\n" +
                "        \"C4\":{\n" +
                "          \"C5\":{\n" +
                "            \"M7\":\"yeah\"\n" +
                "          },\n" +
                "          \"M8\":\"yeah\",\n" +
                "          \"C8\":{\n" +
                "            \"M9\":\"yeah\"\n" +
                "          }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}");

        // 遍历JSON对象
        listParentChild(test, "");
    }

    public static void listParentChild(JSONObject json, String parentPath) {
        // 外层循环：遍历当前JSON对象的所有键
        for (String key : json.keySet()) {

//            System.out.println(json.keySet());
            Object value = json.get(key);
            String currentPath = parentPath.isEmpty() ? key : parentPath + "." + key;

            // 打印当前父子关系
            System.out.println("Parent: " + (parentPath.isEmpty() ? "root" : parentPath) +
                    ", Child: " + key);

            // 内层循环：如果值是JSONObject，则递归处理
            if (value instanceof JSONObject) {
                JSONObject childObj = (JSONObject) value;
                if (!childObj.isEmpty()) {
                    listParentChild(childObj, currentPath);
                }
            }
        }
    }
}
